package cn.practice._07springaop.egaop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class CartAspect {

    /*// 前置通知
    @Before(value = "execution(* cn.practice._07springaop.egaop.CartServiceImpl.*(..))")
    public void beforeMethod() {
        System.out.println("前置通知");
    }

    // 返回通知
    @AfterReturning(value = "execution(* cn.practice._07springaop.egaop.CartServiceImpl.*(..))",returning = "result")
    public void afterReturningMethod(JoinPoint joinPoint, String result) {
        // 获取方法名和方法参数
        String methodName = joinPoint.getSignature().getName();

        System.out.println("返回通知:" + methodName + "方法执行了，结果为：" + result);
    }

    // 异常通知
    @AfterThrowing(value = "execution(* cn.practice._07springaop.egaop.CartServiceImpl.*(..))",throwing = "ex")
    public void afterThrowingMethod(JoinPoint joinPoint, Exception ex) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("异常通知:" + methodName + "方法抛出异常了，异常为：" + ex);
    }

    // 后置通知
    @After(value = "execution(* cn.practice._07springaop.egaop.CartServiceImpl.*(..))")
    public void afterMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("后置通知:" + methodName + "方法彻底执行了");
    }*/

    // 环绕通知
    @Around(value = "execution(* cn.practice._07springaop.egaop.CartServiceImpl.*(..))")
    public Object aroundMethod(ProceedingJoinPoint joinPoint) {
        Object result = null;
        try {
            // 获取方法名
            String methodName = joinPoint.getSignature().getName();
            // 获取参数
            String args = joinPoint.getArgs().toString();
            // 前置通知
            System.out.println("前置通知");

            // 正式执行方法
            result = joinPoint.proceed();

            // 返回通知
            System.out.println("返回通知,结果为：" + result);
        } catch (Throwable throwable) {
            // 异常通知
            System.out.println("异常通知:" + throwable);
        } finally {
            // 后置通知
            System.out.println("后置通知");
        }
        return result;
    }

}
